#coding:utf-8
from flask import current_app, jsonify, make_response, request
from . import api
from ihome.utils.captcha.captcha import captcha
from ihome.utils.response_code import RET
import random
from ihome import redis_store, db
from ihome.models import User
from ihome.utils.constains import REDIS_VERIFY_CODE_EXPIRES, SMS_CODE_EXPIRES
from ihome.libs.yuntongxun.sms import CCP
# from ihome.tasks.send_sms import send_sms
from ihome.tasks.sms.tasks import send_sms

@api.route('/image_code/<image_code_id>')
def get_image(image_code_id):
    name, text, code = captcha.generate_captcha()

    # redis_store.set('image_code_%s' % image_code_id, text)
    # redis_store.expirex('image_code_%s' % image_code_id, REDIS_VERIFY_CODE_EXPIRES)
    try:
        redis_store.setex('image_code_%s' %image_code_id, REDIS_VERIFY_CODE_EXPIRES, text)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.OK, errmsg="保存图片失败")

    res = make_response(code)
    res.headers["Content-Type"] = 'image/jpg'
    return res


# 用celery的
@api.route('/sms_code/<re(r"1[34578]\d{9}"):mobile>')
def get_sms_code(mobile):
    image_code = request.args.get('image_code')
    image_code_id = request.args.get('image_code_id')

    if not all([image_code, image_code_id]):
        return jsonify(errno=RET.PARAMERR, errmsg="参数不完成")
    # 从redis中读取验证码的值
    try:
        real_image_code = redis_store.get("image_code_%s" % image_code_id)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DATAERR, errmsg="读取失败")
    if real_image_code is None:
        return jsonify(errno=RET.DATAERR, errmsg="数据不存在")
    try:
        redis_store.delete("image_code_%s" % image_code_id)
    except Exception as e:
        current_app.error.logger(e)
    if real_image_code.lower() != image_code.lower():
        return jsonify(errno=RET.DATAERR, errmsg="数据校验失败")

    # 检验是否60s内重复登录
    flag = redis_store.get("sms_code_%s" % mobile)
    if flag is not None:
        return jsonify(errno=RET.REQERR, errmsg="请60s后重新操作" )

    try:
        user = User.query.filter_by(mobile=mobile).first()
    except Exception as e:
        current_app.error.logger(e)
    else:
        if user is not None:
            return jsonify(errno=RET.DATAEXIST, errmsg="手机号码已存在")

    sms_code = '%06d' % random.randint(0, 999999)
    try:

        redis_store.setex("sms_code_%s" %mobile, SMS_CODE_EXPIRES, sms_code)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DATAERR, errmsg="保存短信验证码异常")

    send_sms.delay(mobile, [sms_code, SMS_CODE_EXPIRES/60], 1)
    return jsonify(errno=RET.OK, errmsg="发送成功")



# 没有celery的

#
# @api.route('/sms_code/<re(r"1[34578]\d{9}"):mobile>')
# def get_sms_code(mobile):
#     image_code = request.args.get('image_code')
#     image_code_id = request.args.get('image_code_id')
#
#     if not all([image_code, image_code_id]):
#         return jsonify(errno=RET.PARAMERR, errmsg="参数不完成")
#     # 从redis中读取验证码的值
#     try:
#         real_image_code = redis_store.get("image_code_%s" % image_code_id)
#     except Exception as e:
#         current_app.logger.error(e)
#         return jsonify(errno=RET.DATAERR, errmsg="读取失败")
#     if real_image_code is None:
#         return jsonify(errno=RET.DATAERR, errmsg="数据不存在")
#     try:
#         redis_store.delete("image_code_%s" % image_code_id)
#     except Exception as e:
#         current_app.error.logger(e)
#     if real_image_code.lower() != image_code.lower():
#         return jsonify(errno=RET.DATAERR, errmsg="数据校验失败")
#
#     # 检验是否60s内重复登录
#     flag = redis_store.get("sms_code_%s" %mobile)
#     if flag is not None:
#         return jsonify(errno=RET.REQERR, errmsg="请60s后重新操作" )
#
#     try:
#         user = User.query.filter_by(mobile=mobile).first()
#     except Exception as e:
#         current_app.error.logger(e)
#     else:
#         if user is not None:
#             return jsonify(errno=RET.DATAEXIST, errmsg="手机号码已存在")
#
#     sms_code = '%06d' % random.randint(0, 999999)
#     try:
#
#         redis_store.setex("sms_code_%s" %mobile, SMS_CODE_EXPIRES, sms_code)
#     except Exception as e:
#         current_app.logger.error(e)
#         return jsonify(errno=RET.DATAERR, errmsg="保存短信验证码异常")
#
#
#     # 发送短信验证码
#     try:
#         ccp = CCP()
#         result = ccp.sendTemplateSMS(mobile, [sms_code, SMS_CODE_EXPIRES/60], 1)
#     except Exception as e:
#         current_app.logger.error(e)
#         return jsonify(errno=RET.THIRDERR, errmsg="发送异常")
#
#     if result == 0:
#         return jsonify(errno=RET.OK, errmsg="发送成功")
#     else:
#         return jsonify(errno=RET.THIRDERR, errmsg='发送失败')